package com.hnxxxy.oa.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hnxxxy.oa.enums.BizCodeEnum;
import com.hnxxxy.oa.exception.BizException;
import com.hnxxxy.oa.system.mapper.SysRoleMapper;
import com.hnxxxy.oa.system.mapper.SysUserMapper;
import com.hnxxxy.oa.system.model.SysUserRoleDO;
import com.hnxxxy.oa.system.mapper.SysUserRoleMapper;
import com.hnxxxy.oa.system.service.SysUserRoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
* @author 周石林
* @description 针对表【sys_user_role(用户-角色)】的数据库操作Service实现
* @createDate 2022-05-05 16:06:48
*/
@Service
public class SysUserRoleServiceImpl implements SysUserRoleService {

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;

    @Override
    public Integer addUserRole(Integer userId, Integer roleId) {
        if(sysUserMapper.selectById(userId)==null){
            throw new BizException(BizCodeEnum.ACCOUNT_UNREGISTER);
        }
        if(sysRoleMapper.selectById(roleId)==null){
            throw new BizException(BizCodeEnum.ROLE_NOTEXISTS);
        }
        QueryWrapper<SysUserRoleDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("role_id",roleId);
        Integer count = sysUserRoleMapper.selectCount(queryWrapper);
        if(count>0){
            throw new BizException(BizCodeEnum.USER_ROLE_EXIST);
        }
        //构建插入数据库对象
        SysUserRoleDO sysUserRoleDO = new SysUserRoleDO();
        sysUserRoleDO.setUserId(userId);
        sysUserRoleDO.setRoleId(roleId);
        int insert = sysUserRoleMapper.insert(sysUserRoleDO);
        return insert;
    }

    @Override
    public boolean deleteUserRole(Integer userId, Integer roleId) {
        if(userId==null && roleId==null){
            throw new BizException(BizCodeEnum.PARAM_NULL);
        }
        QueryWrapper<SysUserRoleDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(userId!=null,"user_id",userId);
        queryWrapper.eq(roleId!=null,"role_id",roleId);
        int delete = sysUserRoleMapper.delete(queryWrapper);
        return delete==1;
    }
}